package org.momonga1banchi.reminder.server;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.momonga1banchi.reminder.util.DateUtil;
import org.momonga1banchi.reminder.util.MailUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

/**
 * リマインド登録サーブレット
 * 
 * @author momonga1banchi
 * @since 2010/05/18
 */
@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
    private Logger log = Logger.getLogger(this.getClass().getName());
    private DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    private Properties props = new Properties();
    private Session session = Session.getDefaultInstance(props, null);
    private MimeMessage msg = null;

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        try {
            msg = new MimeMessage(session, req.getInputStream());
            Address to = msg.getFrom()[0];
            log.info("to:" + to.toString());
//            String date = new String(msg.getSubject().getBytes("8859_1"), "UTF-8");   // for local
            String date = msg.getSubject();
            log.info("subject:" + date);

            String name = MailUtil.getMailBodyMessage((Part) msg);
            log.info("taskname:" + name);

            if (name == null || name.equals("")) {
                name = "It's time to do what you scheduled.";
            } else if (name.length() > 500) {
                name = name.substring(0, 500);
            }

            String printDate = "";

            try {
                Calendar scheduledTime = DateUtil.makeRemindDate(date);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                String dbDate = sdf.format(scheduledTime.getTime());
                SimpleDateFormat timeParser = new SimpleDateFormat("yyyyMMddHHmm");
                SimpleDateFormat timePrinter = new SimpleDateFormat("yyyy/MM/dd(EEE) HH:mm");

                printDate = timePrinter.format(timeParser.parse(dbDate));
                Entity task = new Entity("task", dbDate + to);
                task.setProperty("date", dbDate);
                task.setProperty("to", to.toString());
                task.setProperty("name", name);
                task.setProperty("done", false);
                ds.put(task);
            } catch (Exception e) {
                log.warning("error occured " + e.getMessage());
                MimeMessage replyMsg = new MimeMessage(session);
                replyMsg.setFrom(new InternetAddress("reply@momonga1banchi.appspotmail.com",
                        "reply@momonga1banchi.appspotmail.com"));
                replyMsg.setRecipient(Message.RecipientType.TO, to);
                replyMsg.setSubject("your request failed", "iso-2022-jp");
                replyMsg.setText("Sorry, we cannot accept your request.\nPlease try again.", "iso-2022-jp");
                Transport.send(replyMsg);
                return;
            }

            MimeMessage replyMsg = new MimeMessage(session);
            replyMsg.setFrom(new InternetAddress("reply@momonga1banchi.appspotmail.com",
                    "reply@momonga1banchi.appspotmail.com"));
            replyMsg.setRecipient(Message.RecipientType.TO, to);
            replyMsg.setSubject("recieved your request", "iso-2022-jp");
            replyMsg.setText("We will accept your request as follows.\ndate:" + printDate + "\n" + name, "iso-2022-jp");
            Transport.send(replyMsg);

        } catch (MessagingException e) {
            log.warning("error occured " + e.getMessage());
        }

    }

}
